/**
 * zy
 */
import GLOBAL from '@/common/js/global.js'
import store from '@/store'
class Ws {
	constructor(url, token) {
		this.socketTask = null;
		this._interval = null;
		this.initWs(url, token);
	}
	initWs(url, token) {
		//websocket start
		this.socketTask = uni.connectSocket({
			url: `${url}?token=${token}`,
			success: () => {
				console.log('socket connect success');
			},
			fail: () => {
				console.error('socket connect fail');
			}
		});
		this.socketTask.onOpen(function(res) {
			console.log('socket连接已打开！');
			this.getOfflineMsg();
			//30秒定时 心跳 bind(this)+>指向当前对象
			this.sendHeartbeat();//立即执行一次
			this._interval = setInterval(this.sendHeartbeat.bind(this), 30000);
		}.bind(this));
		this.socketTask.onError(function(res) {
			console.log('onError:' + res.data);
		});
		this.socketTask.onClose(function() {
			console.log('onClose');
			if (store.state.hasLogin == true) {
				store.state.hasLogin = 'reLogin';
			}
		});
		//websocket end
	}
	closeWs() {
		if (this.socketTask == undefined) {
			return;
		}
		console.log(this._interval, '心跳任务关闭')
		clearInterval(this._interval);
		this.socketTask.close({
			success: () => {
				console.log('socket close success');
				store.state.hasLogin = false;
			},
			fail: () => {
				console.error('socket close fail');
			}
		});
	}
	//发送心跳
	sendHeartbeat() {
		if (!store.state.hasLogin) return;
		let msg = {
			cmd: 13,
			hbbyte: 'this is ok!',
			id: store.state.userInfo.userId + ''
		};
		uni.getLocation({
			success: function(location) {
				msg.extras={
					longitude: location.longitude,
					latitude: location.latitude
				};
				this.send(msg);
			}.bind(this),
			fail:function(e){
				console.error(e.errMsg,'获取坐标 fail');
				this.send(msg);
			}.bind(this)
		});
	};
	send(msg){
		this.socketTask.send({
			data: JSON.stringify(msg), //将json对象转换成字符串,
			success: () => {
				console.log(msg, '发送 success');
			},
			fail: () => {
				console.error('发送 fail');
				this.closeWs();
			}
		});
	};
	//获取离线消息
	getOfflineMsg() {
		if (this.socketTask == undefined) {
			return;
		}
		let msg = {
			cmd: 19,
			userId: uni.getStorageSync(GLOBAL.CacheKeys.userInfo).userId + '',
			type: 0
		};
		this.socketTask.send({
			data: JSON.stringify(msg), //将json对象转换成字符串,
			success: () => {
				console.log('请求发送离线消息 success');
			},
			fail: () => {
				console.error('请求发送离线消息 fail');
			}
		});
	}
}
export default Ws
